package javaTest05.exercise02.client;

import com.alibaba.fastjson.JSON;
import javaTest05.exercise02.dto.MessageDto;
import javaTest05.utils.LogUtils;
import javaTest05.utils.SocketUtils;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

public class ClientReceiveHandler implements Runnable{

    private Socket socket;

    private DataInputStream receive;

    private boolean flag = true;
    public ClientReceiveHandler(Socket socket) throws IOException {
        this.socket = socket;
        receive = new DataInputStream(socket.getInputStream());

        LogUtils.info("客户端收信线程已建立...");
    }

    @Override
    public void run() {
        try {
            while (this.flag){
                String data = receive.readUTF();
                MessageDto messageDto = JSON.parseObject(data, MessageDto.class);
                LogUtils.receive(messageDto);
            }
        }catch (Exception e) {
            LogUtils.error("消息传输异常,客户端已关闭");
            System.exit(0);
        }finally {
            SocketUtils.close(receive);
        }
    }
}
